import os

from jinja2 import Template

from utils.str_utils import to_camel_case


def gen_sync_template_code(table_name, time_field):
    """

    :param table_name: 如,op_order
    :param time_field: 如,created_time
    :return:
    """
    print('table_name', table_name)
    model_name = to_camel_case(table_name)
    service_file_name = f'dev{table_name.replace('op', '').lower()}_service'
    service_name = model_name.replace('Op', '')
    template_code = '''
import os
from typing import List, Any

from models.models_prod import {{model_name}} as Prod{{model_name}}Model
from services.dev.{{service_file_name}} import Dev{{service_name}}Service
from services.prod.prod_service import ProdService
from sync import get_range_time, delete_tag, sync_tag
from sync.base_sync import BaseSync

from utils.log_utils import get_logger

# 获取一个命名的日志记录器
logger = get_logger(__name__, os.path.splitext(os.path.basename(__file__))[0])


class Sync{{service_name}}(BaseSync):
    def insert_dev_data(self, items: List[Any], session=None):
        self.dev_service.add(items, session=session)

    def __init__(self, prod_model_class: ProdService, dev_service: Dev{{service_name}}Service, time_field='{{time_field}}'):
        super().__init__(prod_service=prod_model_class, dev_service=dev_service)
        self.time_field = time_field
        self.dev_service = dev_service


def main(s=None, e=None):
    """

    :param s: 开始时间
    :param e: 结束时间
    """
    try:
        if s and e:
            start, end = s, e
        else:
            start, end = get_range_time()
        logger.info('时间区间: %s 到 %s', start, end)
        prod_service = ProdService(model_class=Prod{{model_name}}Model, time_field='{{time_field}}')
        dev_service = Dev{{service_name}}Service()
        with Sync{{service_name}}(prod_service, dev_service, time_field='{{time_field}}') as syncer:
            syncer.show_total_count(start, end)
            if delete_tag():
                logger.info("删除指定区间的数据")
                syncer.delete_dev_data(start, end)

            if sync_tag():
                logger.info("同步指定区间数据")
                syncer.sync_page(start, end)

    except Exception as e:
        logger.error("主程序异常退出: %s", e, exc_info=True)


if __name__ == '__main__':
    main()
'''
    template = Template(template_code)
    return template.render(service_file_name=service_file_name, service_name=service_name,
                           model_name=model_name, time_field=time_field)


def main_gen_sync_code(model_name, time_field, out_path='../out'):
    sync_code = gen_sync_template_code(model_name, time_field)
    with open(f'{out_path}/sync{model_name.replace("op", "").lower()}.py', 'w') as f:
        f.write(sync_code)


def gen_sync_code():
    from config.config import CONFIG
    tables = CONFIG.get('gen_code')['sync']['gen_code_tables']
    if not tables:
        raise ValueError("Environment variable GEN_CODE_TABLES must be set.")
    try:
        sync_out_path = CONFIG.get('gen_code')['sync']['gen_code_service_out_pat']
    except Exception as e:
        print(e)
        sync_out_path = '../out'
    # 如果文件不存在，则创建
    os.makedirs(sync_out_path, exist_ok=True)
    print(tables)
    for table in tables.split(','):
        sync_name = table
        sync_time_field = 'created_time'
        main_gen_sync_code(sync_name, sync_time_field, sync_out_path)
    print(f'生成完成,sync 路径 {sync_out_path}')


if __name__ == '__main__':
    gen_sync_code()
    print("代码已生成,注意检查:\n1,时间区间的字段是否正确.\n2,需要做 sku 映射的字段,需要添加")
